#include <benchmark/benchmark.h>
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "sys/mman.h"
#include "unistd.h"
#include "util.h"

using namespace std;

static void Bm_function_Mmap(benchmark::State &state)
{
    int fd = open("/data/data/my_mmap.txt", O_RDWR | O_CREAT);
    if (fd == -1)
    {
        perror("open mmap");
        exit(EXIT_FAILURE);
    }
    for (auto _ : state)
    {
        benchmark::DoNotOptimize((char *)mmap(NULL, 128, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0));
    }
    close(fd);
    state.SetItemsProcessed(state.iterations());
}

static void Bm_function_Mmap64(benchmark::State &state)
{
    int fd = open("/data/data/my_mmap64.txt", O_RDWR | O_CREAT);
    if (fd == -1)
    {
        perror("open mmap64");
        exit(EXIT_FAILURE);
    }
    for (auto _ : state)
    {
        benchmark::DoNotOptimize((char *)mmap64(NULL, 128, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0));
    }
    close(fd);
    state.SetItemsProcessed(state.iterations());
}

static void Bm_function_Munmap(benchmark::State &state)
{
    int fd = open("/data/data/my_munmap.txt", O_RDWR | O_CREAT);
    if (fd == -1)
    {
        perror("open munnap");
        exit(EXIT_FAILURE);
    }
    for (auto _ : state)
    {
        char* mem = (char*)mmap(NULL, 8, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
        if (mem != MAP_FAILED)
        {
            benchmark::DoNotOptimize(munmap(mem, 8));
        }
    }
    close(fd);
    state.SetItemsProcessed(state.iterations());
}

MUSL_BENCHMARK(Bm_function_Mmap);
MUSL_BENCHMARK(Bm_function_Mmap64);
MUSL_BENCHMARK(Bm_function_Munmap);